﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace GoodStuff.SharePoint2007
{
    public static class SPWebExtensions
    {
        /// <summary>
        /// Check whether a SPWeb with the given name exists in the given SPWeb
        /// </summary>
        /// <param name="web">The SPWeb to search in</param>
        /// <param name="webName">The name of the SPWeb (case-insentive)</param>
        /// <returns></returns>
        public static bool WebExists(this SPWeb web, string webName)
        {
            return web.Webs.WebExists(webName);
        }

        /// <summary>
        /// Check whether a SPWeb with the given name exists in the given SPWebCollection
        /// </summary>
        /// <param name="webCollection">The SPWeb to search in</param>
        /// <param name="webName">The name of the SPWeb (case-insentive)</param>
        /// <returns></returns>
        public static bool WebExists(this SPWebCollection webCollection, string webName)
        {
            return webCollection.Cast<SPList>().Any(w => string.Compare(w.Title, webName, true) == 0);
        }

        /// <summary>
        /// Check whether the feature with the given ID exists for the given SPWeb.
        /// </summary>
        /// <param name="web">The SPWeb to search in</param>
        /// <param name="featureId">The GUID of the feature</param>
        /// <returns></returns>
        public static bool FeatureActivated(this SPWeb web, Guid featureId)
        {
            return web.Features.Cast<SPFeature>().Any(f => f.DefinitionId == featureId);
        }

        /// <summary>
        /// Check whether the feature with the given name exists for the given SPWeb.
        /// </summary>
        /// <param name="web">The SPWeb to search in</param>
        /// <param name="featureName">The GUID of the feature</param>
        /// <returns></returns>
        public static bool FeatureActivated(this SPWeb web, string featureName)
        {
            return web.Features.Cast<SPFeature>().Any(f => string.Compare(f.Definition.Name, featureName, true) == 0);
        }       
    }
}
